package com.system.main;

import com.system.entity.Admin;
import com.system.entity.Student;
import com.system.entity.Course;
import com.system.entity.Score;
import com.system.entity.DataException;
import com.system.service.AdminService;
import com.system.service.StudentService;
import com.system.service.CourseService;
import com.system.service.ScoreService;

import java.util.Scanner;
import java.util.InputMismatchException;

/**
 * 学生信息管理系统主类
 * 程序入口，提供用户交互界面
 */
public class Main {
    private static Scanner scanner = new Scanner(System.in);
    private static AdminService adminService = new AdminService();
    private static StudentService studentService = new StudentService();
    private static CourseService courseService = new CourseService();
    private static ScoreService scoreService = new ScoreService();

    public static void main(String[] args) {
        System.out.println("欢迎使用学生信息管理系统");
        
        // 登录验证
        if (!login()) {
            System.out.println("登录失败，程序退出");
            return;
        }

        // 主菜单
        while (true) {
            showMainMenu();
            try {
                int choice = scanner.nextInt();
                scanner.nextLine(); // 消费换行符

                switch (choice) {
                    case 1:
                        studentManagement();
                        break;
                    case 2:
                        courseManagement();
                        break;
                    case 3:
                        scoreManagement();
                        break;
                    case 4:
                        System.out.print("是否保存数据？(Y/N): ");
                        String saveChoice = scanner.nextLine();
                        if (saveChoice.equalsIgnoreCase("Y")) {
                            System.out.println("数据已保存");
                        }
                        System.out.println("感谢使用，再见！");
                        return;
                    default:
                        System.out.println("请输入正确的选项");
                }
            } catch (InputMismatchException e) {
                System.out.println("请输入正确的数字格式");
                scanner.nextLine(); // 消费错误输入
            }
        }
    }

    /**
     * 登录功能
     * @return 是否登录成功
     */
    private static boolean login() {
        int attempts = 0;
        while (attempts < 3) {
            try {
                System.out.print("请输入用户名：");
                String username = scanner.nextLine();
                System.out.print("请输入密码：");
                String password = scanner.nextLine();

                if (adminService.login(username, password)) {
                    System.out.println("登录成功！");
                    return true;
                } else {
                    attempts++;
                    System.out.println("账户或密码错误，请重试（剩余" + (3 - attempts) + "次机会）");
                }
            } catch (DataException e) {
                System.out.println("错误：" + e.getMessage());
            }
        }
        return false;
    }

    /**
     * 显示主菜单
     */
    private static void showMainMenu() {
        System.out.println("\n===== 学生信息管理系统 =====");
        System.out.println("1. 学生管理");
        System.out.println("2. 课程管理");
        System.out.println("3. 成绩管理");
        System.out.println("4. 退出");
        System.out.print("请选择：");
    }

    /**
     * 学生管理功能
     */
    private static void studentManagement() {
        while (true) {
            System.out.println("\n===== 学生管理 =====");
            System.out.println("1. 添加学生");
            System.out.println("2. 删除学生");
            System.out.println("3. 修改学生信息");
            System.out.println("4. 按学号查询");
            System.out.println("5. 按班级查询");
            System.out.println("6. 返回上级菜单");
            System.out.print("请选择：");

            try {
                int choice = scanner.nextInt();
                scanner.nextLine(); // 消费换行符

                switch (choice) {
                    case 1:
                        addStudent();
                        break;
                    case 2:
                        deleteStudent();
                        break;
                    case 3:
                        updateStudent();
                        break;
                    case 4:
                        queryStudentById();
                        break;
                    case 5:
                        queryStudentsByClass();
                        break;
                    case 6:
                        return;
                    default:
                        System.out.println("请输入正确的选项");
                }
            } catch (InputMismatchException e) {
                System.out.println("请输入正确的数字格式");
                scanner.nextLine();
            }
        }
    }

    /**
     * 添加学生
     */
    private static void addStudent() {
        try {
            System.out.print("请输入学号：");
            String studentId = scanner.nextLine();
            System.out.print("请输入姓名：");
            String name = scanner.nextLine();
            System.out.print("请输入性别：");
            String gender = scanner.nextLine();
            System.out.print("请输入年龄（15-30）：");
            int age = scanner.nextInt();
            scanner.nextLine(); // 消费换行符
            System.out.print("请输入班级：");
            String className = scanner.nextLine();

            Student student = new Student(studentId, name, gender, age, className);
            studentService.addStudent(student);
            System.out.println("添加成功！");
        } catch (InputMismatchException e) {
            System.out.println("年龄格式错误");
            scanner.nextLine();
        } catch (DataException e) {
            System.out.println("错误：" + e.getMessage());
        }
    }

    /**
     * 删除学生
     */
    private static void deleteStudent() {
        try {
            System.out.print("请输入要删除的学生学号：");
            String studentId = scanner.nextLine();
            System.out.print("确认删除？(Y/N): ");
            String confirm = scanner.nextLine();
            if (confirm.equalsIgnoreCase("Y")) {
                studentService.deleteStudent(studentId);
                System.out.println("删除成功！");
            }
        } catch (DataException e) {
            System.out.println("错误：" + e.getMessage());
        }
    }

    /**
     * 修改学生信息
     */
    private static void updateStudent() {
        try {
            System.out.print("请输入要修改的学生学号：");
            String studentId = scanner.nextLine();
            Student student = studentService.getStudentById(studentId);
            
            System.out.print("请输入新姓名（当前：" + student.getName() + "）：");
            String name = scanner.nextLine();
            if (!name.isEmpty()) {
                student.setName(name);
            }
            
            System.out.print("请输入新性别（当前：" + student.getGender() + "）：");
            String gender = scanner.nextLine();
            if (!gender.isEmpty()) {
                student.setGender(gender);
            }
            
            System.out.print("请输入新年龄（当前：" + student.getAge() + "，15-30）：");
            String ageStr = scanner.nextLine();
            if (!ageStr.isEmpty()) {
                student.setAge(Integer.parseInt(ageStr));
            }
            
            System.out.print("请输入新班级（当前：" + student.getClassName() + "）：");
            String className = scanner.nextLine();
            if (!className.isEmpty()) {
                student.setClassName(className);
            }
            
            studentService.updateStudent(student);
            System.out.println("修改成功！");
        } catch (InputMismatchException | NumberFormatException e) {
            System.out.println("年龄格式错误");
        } catch (DataException e) {
            System.out.println("错误：" + e.getMessage());
        }
    }

    /**
     * 按学号查询学生
     */
    private static void queryStudentById() {
        try {
            System.out.print("请输入学号：");
            String studentId = scanner.nextLine();
            Student student = studentService.getStudentById(studentId);
            
            System.out.println("\n学生信息：");
            System.out.println("学号：" + student.getStudentId());
            System.out.println("姓名：" + student.getName());
            System.out.println("性别：" + student.getGender());
            System.out.println("年龄：" + student.getAge());
            System.out.println("班级：" + student.getClassName());
        } catch (DataException e) {
            System.out.println("错误：" + e.getMessage());
        }
    }

    /**
     * 按班级查询学生
     */
    private static void queryStudentsByClass() {
        System.out.print("请输入班级名：");
        String className = scanner.nextLine();
        Student[] students = studentService.getStudentsByClass(className);
        
        if (students.length == 0) {
            System.out.println("未找到该班级的学生");
        } else {
            System.out.println("\n学生列表：");
            System.out.println("学号\t姓名\t性别\t年龄\t班级");
            for (Student student : students) {
                System.out.println(student.getStudentId() + "\t" + 
                                   student.getName() + "\t" + 
                                   student.getGender() + "\t" + 
                                   student.getAge() + "\t" + 
                                   student.getClassName());
            }
        }
    }

    /**
     * 课程管理功能
     */
    private static void courseManagement() {
        while (true) {
            System.out.println("\n===== 课程管理 =====");
            System.out.println("1. 添加课程");
            System.out.println("2. 删除课程");
            System.out.println("3. 修改课程信息");
            System.out.println("4. 查询所有课程");
            System.out.println("5. 返回上级菜单");
            System.out.print("请选择：");

            try {
                int choice = scanner.nextInt();
                scanner.nextLine(); // 消费换行符

                switch (choice) {
                    case 1:
                        addCourse();
                        break;
                    case 2:
                        deleteCourse();
                        break;
                    case 3:
                        updateCourse();
                        break;
                    case 4:
                        showAllCourses();
                        break;
                    case 5:
                        return;
                    default:
                        System.out.println("请输入正确的选项");
                }
            } catch (InputMismatchException e) {
                System.out.println("请输入正确的数字格式");
                scanner.nextLine();
            }
        }
    }

    /**
     * 添加课程
     */
    private static void addCourse() {
        try {
            System.out.print("请输入课程号：");
            String courseId = scanner.nextLine();
            System.out.print("请输入课程名：");
            String courseName = scanner.nextLine();
            System.out.print("请输入学分（0.5-5.0）：");
            double credit = scanner.nextDouble();
            scanner.nextLine(); // 消费换行符

            Course course = new Course(courseId, courseName, credit);
            courseService.addCourse(course);
            System.out.println("添加成功！");
        } catch (InputMismatchException e) {
            System.out.println("学分格式错误");
            scanner.nextLine();
        } catch (DataException e) {
            System.out.println("错误：" + e.getMessage());
        }
    }

    /**
     * 删除课程
     */
    private static void deleteCourse() {
        try {
            System.out.print("请输入要删除的课程号：");
            String courseId = scanner.nextLine();
            System.out.print("确认删除？(Y/N): ");
            String confirm = scanner.nextLine();
            if (confirm.equalsIgnoreCase("Y")) {
                courseService.deleteCourse(courseId);
                System.out.println("删除成功！");
            }
        } catch (DataException e) {
            System.out.println("错误：" + e.getMessage());
        }
    }

    /**
     * 修改课程信息
     */
    private static void updateCourse() {
        try {
            System.out.print("请输入要修改的课程号：");
            String courseId = scanner.nextLine();
            Course course = courseService.getCourseById(courseId);
            
            System.out.print("请输入新课程名（当前：" + course.getCourseName() + "）：");
            String courseName = scanner.nextLine();
            if (!courseName.isEmpty()) {
                course.setCourseName(courseName);
            }
            
            System.out.print("请输入新学分（当前：" + course.getCredit() + "，0.5-5.0）：");
            String creditStr = scanner.nextLine();
            if (!creditStr.isEmpty()) {
                course.setCredit(Double.parseDouble(creditStr));
            }
            
            courseService.updateCourse(course);
            System.out.println("修改成功！");
        } catch (InputMismatchException | NumberFormatException e) {
            System.out.println("学分格式错误");
        } catch (DataException e) {
            System.out.println("错误：" + e.getMessage());
        }
    }

    /**
     * 显示所有课程
     */
    private static void showAllCourses() {
        Course[] courses = courseService.getAllCourses();
        
        if (courses.length == 0) {
            System.out.println("暂无课程信息");
        } else {
            System.out.println("\n课程列表（按课程号升序）：");
            System.out.println("课程号\t课程名\t学分");
            for (Course course : courses) {
                System.out.println(course.getCourseId() + "\t" + 
                                   course.getCourseName() + "\t" + 
                                   course.getCredit());
            }
        }
    }

    /**
     * 成绩管理功能
     */
    private static void scoreManagement() {
        while (true) {
            System.out.println("\n===== 成绩管理 =====");
            System.out.println("1. 添加成绩");
            System.out.println("2. 修改成绩");
            System.out.println("3. 删除成绩");
            System.out.println("4. 按学号查询成绩");
            System.out.println("5. 按课程号查询成绩");
            System.out.println("6. 返回上级菜单");
            System.out.print("请选择：");

            try {
                int choice = scanner.nextInt();
                scanner.nextLine(); // 消费换行符

                switch (choice) {
                    case 1:
                        addScore();
                        break;
                    case 2:
                        updateScore();
                        break;
                    case 3:
                        deleteScore();
                        break;
                    case 4:
                        queryScoresByStudentId();
                        break;
                    case 5:
                        queryScoresByCourseId();
                        break;
                    case 6:
                        return;
                    default:
                        System.out.println("请输入正确的选项");
                }
            } catch (InputMismatchException e) {
                System.out.println("请输入正确的数字格式");
                scanner.nextLine();
            }
        }
    }

    /**
     * 添加成绩
     */
    private static void addScore() {
        try {
            System.out.print("请输入学号：");
            String studentId = scanner.nextLine();
            System.out.print("请输入课程号：");
            String courseId = scanner.nextLine();
            
            // 验证并获取学生和课程信息
            Student student = studentService.getStudentById(studentId);
            Course course = courseService.getCourseById(courseId);
            
            System.out.print("请输入分数（0-100）：");
            double score = scanner.nextDouble();
            scanner.nextLine(); // 消费换行符
            
            Score scoreRecord = new Score(studentId, student.getName(), courseId, course.getCourseName(), score);
            scoreService.addScore(scoreRecord);
            System.out.println("添加成功！");
        } catch (InputMismatchException e) {
            System.out.println("分数格式错误");
            scanner.nextLine();
        } catch (DataException e) {
            System.out.println("错误：" + e.getMessage());
        }
    }

    /**
     * 修改成绩
     */
    private static void updateScore() {
        try {
            System.out.print("请输入学号：");
            String studentId = scanner.nextLine();
            System.out.print("请输入课程号：");
            String courseId = scanner.nextLine();
            System.out.print("请输入新分数（0-100）：");
            double newScore = scanner.nextDouble();
            scanner.nextLine(); // 消费换行符
            
            scoreService.updateScore(studentId, courseId, newScore);
            System.out.println("修改成功！");
        } catch (InputMismatchException e) {
            System.out.println("分数格式错误");
            scanner.nextLine();
        } catch (DataException e) {
            System.out.println("错误：" + e.getMessage());
        }
    }

    /**
     * 删除成绩
     */
    private static void deleteScore() {
        try {
            System.out.print("请输入学号：");
            String studentId = scanner.nextLine();
            System.out.print("请输入课程号：");
            String courseId = scanner.nextLine();
            System.out.print("确认删除？(Y/N): ");
            String confirm = scanner.nextLine();
            if (confirm.equalsIgnoreCase("Y")) {
                scoreService.deleteScore(studentId, courseId);
                System.out.println("删除成功！");
            }
        } catch (DataException e) {
            System.out.println("错误：" + e.getMessage());
        }
    }

    /**
     * 按学号查询成绩
     */
    private static void queryScoresByStudentId() {
        System.out.print("请输入学号：");
        String studentId = scanner.nextLine();
        Score[] scores = scoreService.getScoresByStudentId(studentId);
        
        if (scores.length == 0) {
            System.out.println("未找到该学生的成绩");
        } else {
            System.out.println("\n成绩列表：");
            System.out.println("学号\t姓名\t课程号\t课程名\t分数");
            for (Score score : scores) {
                System.out.println(score.getStudentId() + "\t" + 
                                   score.getStudentName() + "\t" + 
                                   score.getCourseId() + "\t" + 
                                   score.getCourseName() + "\t" + 
                                   score.getScore());
            }
            double average = scoreService.calculateAverage(scores);
            System.out.println("平均分：" + average);
        }
    }

    /**
     * 按课程号查询成绩
     */
    private static void queryScoresByCourseId() {
        System.out.print("请输入课程号：");
        String courseId = scanner.nextLine();
        Score[] scores = scoreService.getScoresByCourseId(courseId);
        
        if (scores.length == 0) {
            System.out.println("未找到该课程的成绩");
        } else {
            System.out.println("\n成绩列表：");
            System.out.println("学号\t姓名\t课程号\t课程名\t分数");
            for (Score score : scores) {
                System.out.println(score.getStudentId() + "\t" + 
                                   score.getStudentName() + "\t" + 
                                   score.getCourseId() + "\t" + 
                                   score.getCourseName() + "\t" + 
                                   score.getScore());
            }
            double average = scoreService.calculateAverage(scores);
            System.out.println("平均分：" + average);
        }
    }
}